package com.wingtrade.convert.jod.controller;

import com.wingtrade.convert.jod.service.ParameterDecoder;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.document.DocumentFormat;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.core.util.FileUtils;
import org.jodconverter.core.util.StringUtils;
import org.jodconverter.local.LocalConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: lordgod
 * @Date: 2024/9/23 00:04
 */
@Slf4j
@Controller
@RequestMapping("/lool/convert-to")
public class ConverterController {
    private final OfficeManager officeManager;
    private final ParameterDecoder parameterDecoder;


    @Autowired
    public ConverterController(final OfficeManager officeManager, ParameterDecoder parameterDecoder) {
        super();

        this.officeManager = officeManager;
        this.parameterDecoder = parameterDecoder;
    }

    @PostMapping(
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Object convertToUsingParam(
            @RequestParam("data") final MultipartFile inputFile,
            @RequestParam(name = "format") final String convertToFormat,
            @RequestParam(required = false) final Map<String, String> parameters) {

        log.debug("convertUsingRequestParam > Converting file to {}", convertToFormat);
        return convert(inputFile, convertToFormat, parameters);
    }

    @PostMapping(
            value = "/{format}",
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
            produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public Object convertToUsingPath(
            @RequestParam("data") final MultipartFile inputFile,
            @PathVariable(name = "format") final String convertToFormat,
            @RequestParam(required = false) final Map<String, String> parameters) {

        log.debug("convertUsingPathVariable > Converting file to {}", convertToFormat);
        return convert(inputFile, convertToFormat, parameters);
    }

    private ResponseEntity<Object> convert(
            final MultipartFile inputFile,
            final String outputFormat,
            final Map<String, String> parameters) {

        if (inputFile.isEmpty()) {
            return ResponseEntity.badRequest().build();
        }

        if (StringUtils.isBlank(outputFormat)) {
            return ResponseEntity.badRequest().build();
        }

        // Here, we could have a dedicated service that would convert document
        try (ByteArrayOutputStream bass = new ByteArrayOutputStream()) {

            final DocumentFormat targetFormat = DefaultDocumentFormatRegistry.getFormatByExtension(outputFormat);
            Assert.notNull(targetFormat, "targetFormat must not be null");

            // Decode the parameters to load and store properties.
            final Map<String, Object> loadProperties =
                    new HashMap<>(LocalConverter.DEFAULT_LOAD_PROPERTIES);
            final Map<String, Object> storeProperties = new HashMap<>();
            parameterDecoder.decodeParameters(parameters, loadProperties, storeProperties);

            // Create a converter with the properties.
            final DocumentConverter converter =
                    LocalConverter.builder()
                            .officeManager(officeManager)
                            .loadProperties(loadProperties)
                            .storeProperties(storeProperties)
                            .build();

            // Convert...
            converter.convert(inputFile.getInputStream()).to(bass).as(targetFormat).execute();

            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.parseMediaType(targetFormat.getMediaType()));
            headers.add(
                    "Content-Disposition",
                    "attachment; filename="
                            + FileUtils.getBaseName(inputFile.getOriginalFilename())
                            + "."
                            + targetFormat.getExtension());
            return ResponseEntity.ok().headers(headers).body(bass.toByteArray());

        } catch (OfficeException | IOException ex) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex);
        }
    }
}
